<?php

namespace App\Controller\App;

use App\Base\BaseController4Restful;
use App\Entity\Article;
use App\Entity\ChatKey;
use App\Repository\ArticleRepository;
use App\Repository\ChatKeyRepository;
use App\Repository\ChatKeywordRepository;
use App\Repository\ChatRepository;
use App\Repository\CommentRepository;
use App\Repository\ConfigRepository;
use App\Service\MoneyService;
use Symfony\Component\Routing\Annotation\Route;
use function Doctrine\ORM\QueryBuilder;

class ChatController extends BaseController4Restful
{
    /**
     * @Route("/app/single/chat", name="AppSingleChat")
     */
    public function AppSingleChat(
        ChatRepository $chatRepository
        ,ArticleRepository $articleRepository
        ,ConfigRepository $configRepository
        ,MoneyService $moneyService
        ,ChatKeyRepository $chatKeyRepository
        ,ChatKeywordRepository $chatKeywordRepository
    )
    {
        if(!$who = $this->getParamRequired("who")){$who=0;}
        if(!$content = $this->getParamRequired("content")){return $this->json_out(400,"请输入内容");}
        if(!$flag = $this->getParamRequired("flag")){$flag = 1;}

        $user = $this->needToBeUser();
        $chatRepository->chatSingle($user,$who,$content,$flag);
        if ($flag == 2) {
            //--查看此关键词当日查询次数
            $chatKeyCount = $this->getUserCache($content);
            if (!$chatKeyCount && $chatKeyCount !== 0) {
                $chatKeyCount = 0;
            }else{
                $chatKeyCount = (int)$chatKeyCount + 1;
            }
            $this->setUserCache($content,$chatKeyCount);
            if ($chatKeyCount>=3) {
                //不在提供咨询服务
//                $chatRepository->chatSingleReply($who,$user,"此关键词今日已达最多查询次数，已禁止查询",$flag);
                return $this->json_out(201,"此关键词今日已达最多查询次数，已禁止查询");
            }

            //智能咨询立刻回复
            //---首先检索全部匹配的情况
            $findFullMatch = $chatKeywordRepository->findOneBy(array("flag"=>0,"text"=>$content));
            if (!$findFullMatch){
                $qb = $chatKeywordRepository->createQueryBuilder("A");
                //--计数//todo 如果需要随机回复，再计数
                $qb->where(
                    $qb->expr()->like("A.text","'%{$content}%'")
                );
                $qb->andWhere("A.flag = 1");
                $data = $qb->getQuery()->execute();
                if (!$data) {
                    return $this->json_out(201,"请尝试换一个关键词c");
                }
                $chatRuleKeywords = $data[0];
            }else{
                $chatRuleKeywords = $findFullMatch;
            }


            if ($chatRuleKeywords) {
                $chatRule = $chatRuleKeywords->getRule();
                $list= $chatRule->getReply();
                if ($chatRule->getReplyType() == 1) {
                    //随机回复一条
                    $count = count($list);
                    $rnd = rand(1,$count);
                    $list = [$list[$rnd-1]];
                }

//                /**@var $list ChatKey*/
//                $list = $data[0];
//                $content = $this->serializer->serialize($list->getArts()->getValues(),"json");
                $chatRepository->chatSingleReply($who,$user,json_encode($list),$flag);

                //计费
//                $fee = $configRepository->getByK("FEE_CHAT_AUTO");
//                $fee = $list->getPrice();
                $fee = $chatRule->getPrice();
                if (!$fee) {
                    $fee = 1;
                }
                $fee = $fee * pow(2,$chatKeyCount);


                $userMoney = $moneyService->getUserMoney($user);
                if ($userMoney["jifen"] < $fee) {
                    return $this->json_out(201,"积分不足");
                }

                $moneyService->mod($user,$fee *-1,MoneyService::__MONEY_JI_FEN__,203,"自助咨询");


                //返回的结果为文章列表

                return $this->json_out(200,"OK",$list);
            }else{
                return $this->json_out(201,"请换一个关键词");
            }
        }


        return $this->json_out(200,"OK","");
    }
    /**
     * @Route("/app/single/chat/list", name="AppSingleChatList")
     */
    public function AppSingleChatList(ChatRepository $chatRepository)
    {
        if(!$who = $this->getParamRequired("who")){$who=0;}
        if(!$lastId = $this->getParamRequired("lastId")){$lastId = 0;}
        if(!$flag = $this->getParamRequired("flag")){$flag = 1;}
//        flag 1=一对一人工服务，2=智能回复
        $user = $this->needToBeUser();
        $data = $chatRepository->getList($user->getId(),$who,$flag,$lastId);

        $this->setGroups("chat","user");

        $data = $this->serialize($data);
        foreach ($data as &$row) {
            if (!$row["fromUser"]) {//平台回复
                $row["type"] = 0;
                if ($flag == 2) {
                    $row["content"] = json_decode($row["content"],true);
                }
            }else{
                $row["type"] = 1;
            }
        }

//        dd($data);

        return $this->json_out(200,"OK",$data);
    }



}
